//
//  DetailListController.m
//  SeeFood
//
//  Created by 陈伟捷 on 15/11/24.
//  Copyright © 2015年 纪洪波. All rights reserved.
//

#import "DetailListController.h"
#import "DetailListCell.h"

@interface DetailListController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)NSMutableArray *modelArray;

@property(nonatomic, strong)UITableView *tableView;

@end

@implementation DetailListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.tableView registerClass:[DetailListCell class] forCellReuseIdentifier:@"detailListCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    NSString *urlString = nil;
    if (_isPushed) {
        urlString = _search;
    }else{
    urlString = [NSString stringWithFormat:@"http://apis.juhe.cn/cook/index?key=b38444bae8b8b53d67ae80cf4b81c9d5&cid=%@", self.model.listId];
    }
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSDictionary *resultDic = dic[@"result"];
        
        NSArray *dataArray = resultDic[@"data"];
        
        self.modelArray = [NSMutableArray array];
        
        for (NSDictionary *dic in dataArray) {
            
            DetailListModel *model = [[DetailListModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }] resume];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.modelArray != nil) {
        return self.modelArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailListCell" forIndexPath:indexPath];
    
    DetailListModel *model = _modelArray[indexPath.row];
    
    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [DetailListCell rowHeight:_modelArray[indexPath.row]];
}

@end
